//
//  UILocalNotification+setAlarmclock.m
//  AlarmClock
//
//  Created by aaaa on 2016/10/13.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "UILocalNotification+setAlarmclock.h"

@implementation UILocalNotification (setAlarmclock)

+(UILocalNotification *)setNextAlrmClockWhithInfoDic:(NSDictionary *)dic{
    if ([dic[@"repeat"] isEqualToString:@"只响一次"]) {
        NSLog(@"只响一次，不设置下一个闹钟");
        return nil;
    }
    ;
    NSLog(@"设置下一次的闹钟-");
    return [UILocalNotification createAlrmClockWhithInfoDic:dic];
}

+(NSDictionary * )setNextAlrmClockWhithInfoDic:(NSDictionary*)dic MoreTime:(NSInteger)minutes{
    UILocalNotification * alarmNoti = [UILocalNotification setNextAlrmClockWhithInfoDic:dic];
    
    NSString * noteString = dic[@"label"];
    //新建一个本地通知
    UILocalNotification *locNoti = [[UILocalNotification alloc]init];
    
    //1.设置通知的必须项
    //1.1 设置通知的内容
    locNoti.alertBody = noteString;
    NSDate * fireDate = [NSDate dateWithTimeIntervalSinceNow:minutes*60];    //1.2 设置通知的发送时间
    locNoti.fireDate = fireDate;
    //设置重复时间
    locNoti.repeatInterval = NSCalendarUnitMinute;
    NSMutableDictionary * mdic = [dic mutableCopy];
    mdic[@"type"] = @"moreTime";
    locNoti.userInfo = [mdic copy];
    //1.3 设置时区,一般默认
    locNoti.timeZone = [NSTimeZone defaultTimeZone];
    //1.4 设置弹框的启动图片(无论此处填什么, 都只是读取默认的启动图片)
    // (iOS9.0之后, 就没有效果)
    locNoti.alertLaunchImage = @"timer_btn_ring_normal.png";
    
    //1.5 设置弹框的标题
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.2) {
        locNoti.alertTitle = @"时间到了！！";
    }
    
    // 设置滑动解锁的文字
    locNoti.hasAction = YES; // 如果是NO,则下面配置的字符串提醒, 没有效果
    locNoti.alertAction = @"时间到了！！";
    
    // 设置通知接收到时的声音(30s)
    NSString * bell = dic[@"bell"];
    if (!bell) {
        bell = @"fallbackring";
    }
    locNoti.soundName = [NSString stringWithFormat:@"%@.wav" ,bell] ;
    
    // 设置通知发送时, 提醒数字(==0, 会自动消失)
    locNoti.applicationIconBadgeNumber = -1;
    
    // 2. 发送通知
    // 通知是一个应用程序级别的操作, openURL
    // 立即推送一个通知
    //    [[UIApplication sharedApplication]presentLocalNotificationNow:locNoti];
    [[UIApplication sharedApplication]scheduleLocalNotification:locNoti];
    
    NSDateFormatter * aformater = [[NSDateFormatter alloc]init];
    [aformater setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    NSLog(@"再响时间:%@\n%@",[aformater stringFromDate:fireDate],dic);
    if (alarmNoti) {
        return @{@"moreTimeNotify":locNoti,@"alarmClockNotify":alarmNoti};
    }else{
        return @{@"moreTimeNotify":locNoti};
    }
}

+(UILocalNotification * )createAlrmClockWhithInfoDic:(NSDictionary*)dic {
    NSString * LNotifyID = dic[@"alarmClockId"];
    NSString * dateString = dic[@"date"];
    NSString * repeatString = dic[@"repeat"];
    NSString * noteString = dic[@"label"];
    
    for (UILocalNotification *noti in [UIApplication sharedApplication].scheduledLocalNotifications) {
        NSString * ID = noti.userInfo[@"alarmClockId"];
        NSString * type = noti.userInfo[@"type"];
        
        if (ID && [ID isEqualToString:LNotifyID] && !type) {
            NSLog(@"已经存在闹钟，无需再设置：\n%@",noti.userInfo);
            return noti;
        }
    }
    
    NSDate * fireDate;
    NSArray * timearray = [dateString componentsSeparatedByString:@":"];
    NSInteger hours = [[timearray firstObject] integerValue];
    NSInteger minutes = [[timearray lastObject] integerValue];
    NSInteger seconds = hours*3600+minutes*60;
    NSArray * repeadArray = nil;
    if (![repeatString isEqualToString:@"只响一次"]) {
        repeadArray = [repeatString componentsSeparatedByString:@"|"];
    }
    
    NSInteger days = -1;
        
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate * now=[NSDate date];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday |
    NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    comps = [calendar components:unitFlags fromDate:now];
    NSInteger CurentWeek = [comps weekday];
    NSInteger CurentHour = [comps hour];
    NSInteger CurentMin = [comps minute];
    NSInteger CurentSec = [comps second];
    NSInteger curentSeconds = CurentHour *3600 +CurentMin*60 +CurentSec;
    
    if (repeadArray) {
        NSArray * arrWeek=@[@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六"];
        for (NSInteger i = 0; i<7; i++) {
            for (NSString * str in repeadArray) {
                if ([str isEqualToString:arrWeek[(CurentWeek+i-1)%7]]) {
                    if (i==0) {
                        if (curentSeconds < seconds) {
                            days = i;
                            break;
                        }
                    }else{
                        days = i;
                        break;
                    }
                }
            }
            if (days!=-1) {
                break;
            }
        }
        if(days==-1){
            days = 7;
        }
    }else{
        if (curentSeconds < seconds) {
            days = 0;
        }else{
            days = 1;
        }
    }

    NSLog(@"下一次闹钟，再过%ld天",days);
    if (days == 0) {
        fireDate = [NSDate dateWithTimeInterval:seconds-curentSeconds sinceDate:now];
    }
    else{
        fireDate = [NSDate dateWithTimeInterval:(24*(days-1))*3600 +(24*3600-curentSeconds)+seconds sinceDate:now];
    }
    
    //新建一个本地通知
    UILocalNotification *locNoti = [[UILocalNotification alloc]init];
    
    //1.设置通知的必须项
    //1.1 设置通知的内容
    locNoti.alertBody = noteString;
    
    //1.2 设置通知的发送时间
    locNoti.fireDate = fireDate;
    //设置重复时间
    locNoti.repeatInterval = NSCalendarUnitMinute;
    
    NSMutableDictionary * mdic = [dic mutableCopy];
    [mdic removeObjectForKey:@"type"];
    
    locNoti.userInfo = [mdic copy];
    //1.3 设置时区,一般默认
    locNoti.timeZone = [NSTimeZone defaultTimeZone];
    //1.4 设置弹框的启动图片(无论此处填什么, 都只是读取默认的启动图片)
    // (iOS9.0之后, 就没有效果)
    locNoti.alertLaunchImage = @"timer_btn_ring_normal.png";
    
    //1.5 设置弹框的标题
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.2) {
        locNoti.alertTitle = @"时间到了！！";
    }
    
    // 设置滑动解锁的文字
    locNoti.hasAction = YES; // 如果是NO,则下面配置的字符串提醒, 没有效果
    locNoti.alertAction = @"时间到了！！";
    
    // 设置通知接收到时的声音(30s)
    NSString * bell = dic[@"bell"];
    if (!bell) {
        bell = @"fallbackring";
    }
    locNoti.soundName = [NSString stringWithFormat:@"%@.wav" ,bell];
    
    // 设置通知发送时, 提醒数字(==0, 会自动消失)
    locNoti.applicationIconBadgeNumber = -1;
    
    // 2. 发送通知
    // 通知是一个应用程序级别的操作, openURL
    // 立即推送一个通知
    //    [[UIApplication sharedApplication]presentLocalNotificationNow:locNoti];
    [[UIApplication sharedApplication]scheduleLocalNotification:locNoti];
    NSDateFormatter * aformater = [[NSDateFormatter alloc]init];
    [aformater setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    NSLog(@"创建闹钟:%@\n%@",[aformater stringFromDate:fireDate],locNoti.userInfo);
    return locNoti;
}
@end
